package com.example.mister5aside;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.sql.Date;
import java.util.Calendar;
import java.util.Timer;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils.StringSplitter;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
	Bundle bundle = new Bundle();
	TextView min,sec,halfTime;
	MyCounter timer;
	Button start, stop;
	int status;
	long orig;
	static int GOAL1;
	static int GOAL2;
	static int FOUL1;
	static int FOUL2;
	static int TIMEOUT1;
	static int TIMEOUT2;
	static int STATUS;
	static int HALFTIME;
	static CharSequence[] players;
	static CharSequence[] playing;
	static int[] positions = new int[10];
	static long[] mills;
	static int[] goals;
	static long currentMillis;

	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.activity_main);

    	status = 0;
    	HALFTIME=1;
    	bundle.putInt("time_long", 25);

    	start = (Button)findViewById(R.id.start);
    	halfTime  = (TextView)findViewById(R.id.halfTime);
    	min  = (TextView)findViewById(R.id.min);
    	sec  = (TextView)findViewById(R.id.seconds);
    	min.setText(bundle.getInt("time_long")+""); // starting from 10.
    	sec.setText("0");
        players = new CharSequence[10];
        playing = new CharSequence[5];
        positions = new int[10];
        mills = new long[10];
        goals = new int[10];
        currentMillis=0;
        loadPlayers();
    }
 
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Always call the superclass so it can restore the view hierarchy
        super.onRestoreInstanceState(savedInstanceState);
        //TextView text_name;
    	GOAL1=savedInstanceState.getInt("goal1");
		final TextView text_name = (TextView) findViewById(R.id.goal1);
		text_name.setText(String.valueOf(GOAL1));
		
        GOAL2=savedInstanceState.getInt("goal2");
        final TextView text_name2 = (TextView) findViewById(R.id.goal2);
		text_name2.setText(String.valueOf(GOAL2));
		
		FOUL1=savedInstanceState.getInt("foul1");
        final TextView text_name3 = (TextView) findViewById(R.id.foul1);
		text_name3.setText(String.valueOf(FOUL1));
		
		FOUL2=savedInstanceState.getInt("foul2");
        final TextView text_name4 = (TextView) findViewById(R.id.foul2);
		text_name4.setText(String.valueOf(FOUL2));

		TIMEOUT1=savedInstanceState.getInt("timeout1");
        final TextView text_name5 = (TextView) findViewById(R.id.timeOut1);
		text_name5.setText(String.valueOf(TIMEOUT1));
		
		TIMEOUT2=savedInstanceState.getInt("timeout2");
        final TextView text_name6 = (TextView) findViewById(R.id.timeOut2);
		text_name6.setText(String.valueOf(TIMEOUT2));
		
		HALFTIME=savedInstanceState.getInt("halfTime");
        final TextView text_name7 = (TextView) findViewById(R.id.halfTime);
		text_name7.setText(String.valueOf(HALFTIME));
		
		status = savedInstanceState.getInt("status");
    	if (savedInstanceState.getInt("status") == 1){
    		orig=savedInstanceState.getLong("origMillis")-(System.currentTimeMillis()-savedInstanceState.getLong("currentMillis"));
    		timer = new MyCounter(orig,1000);
    		timer.start();
    		status = 1;
    		start.setText("PAUSA");
    	}
    	
    	positions = savedInstanceState.getIntArray("positions");
    	goals = savedInstanceState.getIntArray("goals");
    	
    	currentMillis=savedInstanceState.getLong("currentMillis");

    	mills = savedInstanceState.getLongArray("mills");
    	reloadPlayers();
    }
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        //savedInstanceState=bundle;
    	savedInstanceState.putInt("goal1", GOAL1);
    	savedInstanceState.putInt("goal2", GOAL2);
    	savedInstanceState.putInt("foul1", FOUL1);
    	savedInstanceState.putInt("foul2", FOUL2);
    	savedInstanceState.putInt("timeout1", TIMEOUT1);
    	savedInstanceState.putInt("timeout2", TIMEOUT2);
    	savedInstanceState.putInt("halfTime", HALFTIME);
    	savedInstanceState.putLong("currentMillis", currentMillis);
    	savedInstanceState.putLong("origMillis", orig);
    	savedInstanceState.putInt("status", status);
    	savedInstanceState.putIntArray("positions", positions);
    	savedInstanceState.putIntArray("goals", goals);
    	savedInstanceState.putLongArray("mills", mills);
    	//team_intent.putExtra("players", players);

        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }

    public void loadPlayers(){
    	int j=0;
    	players[0]="Antonio";
    	players[1]="Fabio";
    	players[2]="Alessandro";
    	players[3]="Valentino";
    	players[4]="Simone";
    	players[5]="Sakybou";
    	players[6]="Denis";
    	players[7]="Patrik";
    	players[8]="David";
    	players[9]="Leonardo";
    	for (int i = 0; i < positions.length; i++) {
			positions[i]=i;
			goals[i]=0;
			mills[i]=0;	
			if(positions[i]<5)
				playing[j]=players[i];
				j++;
		}
    }
    
    public void reloadPlayers(){
    	for (int i = 0; i < playing.length; i++) {
			playing[i]=players[positions[i]];
		}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
    	switch (item.getItemId()) {
		case R.id.action_settings:
			start_settings();
			break;
		case R.id.action_share:
			start_share();
			break;
//		case R.id.action_save:
//			try {
//				start_save();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			break;
		default:
			break;
		}
    	return false;
    }
    
    public void start_settings() {
    	Intent settings_intent = new Intent(getApplicationContext(),SettingsActivity.class);

    	startActivityForResult(settings_intent, 1);

    }
    
    public void start_save() throws IOException {

//		File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
//		file.createNewFile();
//		String[] data1={1,1,0,0};
//		//write the bytes in file
//		if(file.exists())
//		{
//		     OutputStream fo = new FileOutputStream(file);              
//		     fo.write(data1);
//		     fo.close();
//		     System.out.println("file created: "+file);
//		     url = upload.upload(file);
//		}
//    	File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Download" + File.separator + "test.txt");
//    	System.out.println(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
//		//File myFile = new File("/sdcard/mysdfile.txt");
//		//myFile.createNewFile();
//		FileOutputStream fOut = new FileOutputStream(myFile);
//		OutputStreamWriter myOutWriter = 
//								new OutputStreamWriter(fOut);
//		myOutWriter.append("test");
//		myOutWriter.close();
//		fOut.close();
//		
//		String FILENAME = "/storage/sdcard0/Download/hallo.txt";
//		String string = "hello world!";
//
//		FileOutputStream fos = openFileOutput(FILENAME);
//		fos.write(string.getBytes());
//		fos.close();

    }
    
    public void start_share(){

    	
    	Intent intent=new Intent(android.content.Intent.ACTION_SEND);
    	intent.setType("text/plain");
    	intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    	//String currentDateTimeString = DateFormat.getDateFormat(context)getDateTimeInstance().format(new Date());
    	String report;

    	report = "Report Partita\r\n";
    	report = report + "linea2\r\n";
    	report = report + "linea3";
    	// Add data to the intent, the receiving app will decide what to do with it.
    	intent.putExtra(Intent.EXTRA_SUBJECT, "Some Subject Line");
    	intent.putExtra(Intent.EXTRA_TEXT, report);

    	startActivity(Intent.createChooser(intent, "How do you want to share?"));
    }
    
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    	if (requestCode == 1) {

    		if(resultCode == RESULT_OK){      
    			bundle.putInt("time_long", data.getIntExtra("time_long", 25));

    			min.setText(bundle.getInt("time_long")+"");
    		}
    		if (resultCode == RESULT_CANCELED) {    
    			//Write your code on no result return 
    		}
    	}
    	if (requestCode == 2) {
    		if(resultCode == RESULT_OK || resultCode == RESULT_CANCELED){ 
    			positions=data.getIntArrayExtra("positions");
    			reloadPlayers();
    		}
    	}
    }//onActivityResult
    
    public void team(View v)
    {
    	Intent team_intent = new Intent(getApplicationContext(),TeamActivity.class);
    	team_intent.putExtra("players", players);
    	team_intent.putExtra("positions", positions);
    	team_intent.putExtra("goals", goals);
    	if(status==1){ //Aggiorno se sono avviato e non in pausa
    		for (int i = 0; i < playing.length; i++) {
    			mills[positions[i]]=mills[positions[i]]+(System.currentTimeMillis()-currentMillis);
    		}
    		currentMillis=System.currentTimeMillis();
    	}
    	
		team_intent.putExtra("mills", mills);
    	startActivityForResult(team_intent, 2);
    }

    public void start(View v)
    {
//    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//    String syncConnPref = sharedPref.getString("time_long", "");
    	if (status == 0){
    		timer = new MyCounter(bundle.getInt("time_long")*60*1000,1000);
    		timer.start();
    		status = 1;
    		start.setText("PAUSA");
    		currentMillis=System.currentTimeMillis();
    	}
    	else if(status == 1 ){
    		timer.cancel();
    		status=2;
    		start.setText("RESUME");
    		for (int i = 0; i < playing.length; i++) {
    			mills[positions[i]]=mills[positions[i]]+(System.currentTimeMillis()-currentMillis);
    		}
    	}
    	else if(status == 2 ){
    		//timer.onTick(orig); 
    		timer = new MyCounter(orig, 1000);
    		timer.start();
    		status=1; 
    		start.setText("PAUSA");
    		currentMillis=System.currentTimeMillis();
    	}
    }
    public void stop(View v)
    {
//    	timer.cancel();
//    	status = 0;
//    	start.setText("START");
    }
    
    public void addGoal1(View v)
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("GOAL?")
    	.setItems(playing, new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int which) {
    			// The 'which' argument contains the index position
    			// of the selected item
    			GOAL1=GOAL1+1;
    			goals[positions[which]]=goals[positions[which]]+1;
    			final TextView text_name = (TextView) findViewById(R.id.goal1);
    			text_name.setText(String.valueOf(GOAL1));
    		}
    	});
    	AlertDialog alert =builder.create();
    	alert.show();
    }
    
    public void addGoal2(View v)
    {
    	AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
    	myAlertDialog.setTitle("GOAL?");
    	myAlertDialog.setMessage("");

    	myAlertDialog.setPositiveButton("SI", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			// do something when the OK button is clicked
    			GOAL2=GOAL2+1;
    			//Toast.makeText(this, getTitle(), Toast.LENGTH_LONG).show();
    			final TextView text_name = (TextView) findViewById(R.id.goal2);
    			text_name.setText(String.valueOf(GOAL2));
    		}});

    	myAlertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			// do something when the Cancel button is clicked
    		}});

    	myAlertDialog.show();

    }
    
    public void addFoul1(View v)
    {
    	AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
    	myAlertDialog.setTitle("FALLO?");
    	myAlertDialog.setMessage("");

    	myAlertDialog.setPositiveButton("SI", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			// do something when the OK button is clicked
    			FOUL1=FOUL1+1;
    	    	//Toast.makeText(this, getTitle(), Toast.LENGTH_LONG).show();
    	    	final TextView text_name = (TextView) findViewById(R.id.foul1);
    	    	text_name.setText(String.valueOf(FOUL1));
    		}});

    	myAlertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			// do something when the Cancel button is clicked
    		}});

    	myAlertDialog.show();

    }
    
    public void addFoul2(View v)
    {
    	AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
    	myAlertDialog.setTitle("FALLO?");
    	myAlertDialog.setMessage("");

    	myAlertDialog.setPositiveButton("SI", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			// do something when the OK button is clicked
    			FOUL2=FOUL2+1;
    	    	//Toast.makeText(this, getTitle(), Toast.LENGTH_LONG).show();
    	    	final TextView text_name = (TextView) findViewById(R.id.foul2);
    	    	text_name.setText(String.valueOf(FOUL2));
    		}});

    	myAlertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			// do something when the Cancel button is clicked
    		}});

    	myAlertDialog.show();

    }
    
    public void addTimeout1(View v)
    {
    	AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
    	myAlertDialog.setTitle("TIMEOUT?");
    	myAlertDialog.setMessage("");

    	myAlertDialog.setPositiveButton("SI", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			TIMEOUT1=TIMEOUT1+1;
    	    	final TextView text_name = (TextView) findViewById(R.id.timeOut1);
    	    	text_name.setText(String.valueOf(TIMEOUT1));
    		}});

    	myAlertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			// do something when the Cancel button is clicked
    		}});

    	myAlertDialog.show();

    }
    
    public void addTimeout2(View v)
    {
    	AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
    	myAlertDialog.setTitle("TIMEOUT?");
    	myAlertDialog.setMessage("");

    	myAlertDialog.setPositiveButton("SI", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			TIMEOUT2=TIMEOUT2+1;
    	    	final TextView text_name = (TextView) findViewById(R.id.timeOut2);
    	    	text_name.setText(String.valueOf(TIMEOUT2));
    		}});

    	myAlertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface arg0, int arg1) {
    			// do something when the Cancel button is clicked
    		}});

    	myAlertDialog.show();

    }
    


    public class MyCounter extends CountDownTimer{

    	public MyCounter(long millisInFuture, long countDownInterval) {
    		super(millisInFuture, countDownInterval);
    	}
    	
        public void onPause() {  
            //do stuff later  
            onPause(); 
        }//finish  
        
    	@Override
    	public void onFinish() {
    		System.out.println("Timer Completed.");
    		if(HALFTIME==1){
    			start.setText("START 2°");
    			min.setText("25");
    			sec.setText("0");
    			halfTime.setText("2");
    			HALFTIME=2;
    			status=0;
        		for (int i = 0; i < playing.length; i++) {
        			mills[positions[i]]=mills[positions[i]]+(System.currentTimeMillis()-currentMillis);
        		}
        		FOUL1=0;
    	    	final TextView text_name = (TextView) findViewById(R.id.foul1);
    	    	text_name.setText(String.valueOf(FOUL1));
    	    	FOUL2=0;
    	    	final TextView text_name1 = (TextView) findViewById(R.id.foul2);
    	    	text_name1.setText(String.valueOf(FOUL2));
    		}
    		else if(HALFTIME==2){
    			start.setText("FINISH");
    			HALFTIME=1;
    			status=0;
        		for (int i = 0; i < playing.length; i++) {
        			mills[positions[i]]=mills[positions[i]]+(System.currentTimeMillis()-currentMillis);
        		}
    		}
    	}

    	@Override
    	public void onTick(long millis) {
    	    long seconds = millis / 1000;  
    	    long minutes = seconds / 60;  
    	    orig = millis;
    	    seconds = seconds % 60;  
    	    minutes = minutes % 60; 
    		min.setText(minutes+"");
    		sec.setText(seconds+"");
//    		for (int i = 0; i < playing.length; i++) {
//				mills[positions[i]]++;
//			}
     	}
    }
}
